/**
 * 工具类
 */
import locales from './i18u/locales'
import T from './i18u/index'
import event from './i18u/events'
import {
  defaultShow,
  slideupshow
} from './cssTransition/index'
const app = getApp();
//处理错误提示
const showErrMsg = function (res) {
  let result = "";
  if (res && res.message && typeof (res.message) === "string" && res.message.length > 0) {
    result = res.message;
  } else if (res && res.Message && typeof (res.Message) === "string" && res.Message.length > 0) {
    result = res.Message;
  } else if (res && res.errorMessage && typeof (res.errorMessage) === "string" && res.errorMessage.length > 0) {
    result = res.errorMessage;
  } else if (typeof (res) === "string") {
    result = res;
  } else {
    result = JSON.stringify(res)
  }

  return result.replace(/request:fail|。|！|!/gi, "");
}


/**
 * 提示弹出框(一般用于错误提示)(使用时如果要用then函数，里面不要写有判断标志状态的内容，否则多个弹框同时出现，但只显示一个，其余then里面的代码不执行会造成错误。)
 * @param {*} res 
 * @param {*} title 
 * @param {*} btnText 
 */
export function showFailModal(res, title = "提示", btnText = "确认") {
  if (res) {
    if (res.status == 401) { //登录已失效的情况
      wx.showModal({
        title: title,
        content: res.message,
        showCancel: false,
        confirmText: btnText,
        complete: function () {
          wx.clearStorage();
        }
      });
      return {
        then: () => {
          return;
        }
      }
    } else {
      return new Promise(function (resolve, reject) {
        wx.showModal({
          title: title,
          content: showErrMsg(res),
          showCancel: false,
          complete: function () {
            resolve();
          }
        });
      })
    }
  } else {
    return {
      then: function () {
        return;
      }
    }
  }
}

/**
 * 确定域名
 * @param {*} url 
 */
export function enSureUrl(url) {
  let otherUrl = wx.getStorageSync('domain');
  if (otherUrl) { //自定义域名
    return domain + otherUrl;
  } else {
    return domain + url;
  }
}

/**
 * 根据当前设备语言 || 设置语言的语言改变小程序语言
 * @param {*} lang 当前语言
 */
export function changeSystemLanguage(lang) {
  T.registerLocale(locales);
  T.setLocaleByIndex(wx.getStorageSync('langIndex') || 0);
  wx.T = T;
  lang === 'zh_CN' ? wx.T.setLocaleByIndex(0) : wx.T.setLocaleByIndex(1);
}

/**
 * 提前发起授权请求
 */
export function getAuthorize(scope = '') {
  return new Promise((resolve, reject) => {
    wx.authorize({
      scope: scope,
      success: res => {
        resolve(res);
      },
      fail: err => {
        reject(err);
      }
    })
  })
}

/**
 * 设置页面title和bgcolor
 */
export function setPageTitleAndBgcolor(title, bgcolor) {
  let app = getApp();
  wx.showNavigationBarLoading();
  wx.setNavigationBarTitle({
    title: title,
    success: () => {
      wx.setNavigationBarColor({
        backgroundColor: bgcolor,
        frontColor: app.globalData.systemConfig.theme == 'dark' ? '#ffffff' : '#000000',
        success: () => {
          wx.hideNavigationBarLoading();
        },
        fail: err => {
          console.log(err);
        }
      })
    },
  })

}

//判断Android和ios,   1：Android 2：IOS
export function getDeviceType() {
  let system = wx.getSystemInfoSync().system;
  let firstChar = system.substr(0, 1).toLocaleUpperCase();
  if (firstChar === "A") {
    return 1;
  } else if (firstChar === "I") {
    return 2;
  } else {
    return 2;
  }

}

/**
 * 检查手机定位 || 蓝牙状态
 * @param {String} type 'location' || 'blue'
 */
export function checkDeviceStatus(type = 'location') {
  return new Promise((resolve, reject) => {
    //状态
    let code = {
      200: '已开启',
      500: '未开启',
      401: '未授权',
      400: '已授权'
    };
    let desc;
    let deviceType = getDeviceType();
    wx.getSystemInfo({
      success: res => {
        deviceType == 1 ? desc = ['下拉/上滑找到【定位】开启', '前往手机【设置】找到【隐私保护/隐私】，选择开启【定位/位置信息】'] : desc = ['前往手机【设置】-【隐私】-【定位服务】，点击打开'];
        if (type == 'location') {
          if (res.locationEnabled && res.locationAuthorized) {
            resolve({
              type: 'location',
              desc: [],
              content: [{
                icon: 'checked',
                color: "#02DD5B",
                text: '当前定位' + code[200]
              }, {
                icon: 'checked',
                color: "#02DD5B",
                text: '定位服务' + code[400]
              }],
              button: {
                type: 200,
                text: '确定'
              }
            })
          } else if (res.locationEnabled && !res.locationAuthorized) {
            reject({
              type: 'location',
              desc: [],
              content: [{
                icon: 'checked',
                color: "#02DD5B",
                text: '当前定位' + code[200]
              }, {
                icon: 'clear',
                color: 'red',
                text: '定位服务' + code[401]
              }],
              button: {
                type: 401,
                text: '前往授权定位'
              }
            })
          } else if (!res.locationEnabled && res.locationAuthorized) {
            reject({
              type: 'location',
              desc: desc,
              content: [{
                icon: 'clear',
                color: 'red',
                text: '当前定位' + code[500]
              }, {
                icon: 'checked',
                color: "#02DD5B",
                text: '定位服务' + code[400]
              }],
              button: {
                type: 500,
                text: '确定'
              }
            })
          } else if (!res.locationEnabled && !res.locationAuthorized) {
            reject({
              type: 'location',
              desc: desc,
              content: [{
                icon: 'clear',
                color: 'red',
                text: '当前定位' + code[500]
              }, {
                icon: 'clear',
                color: 'red',
                text: '定位服务' + code[401]
              }],
              button: {
                type: 500,
                text: '确定'
              }
            })
          }
          //蓝牙
        } else {
          //Android 无法检查是否授权，但是能跳转系统蓝牙
          if (deviceType == 1) {
            if (res.bluetoothEnabled) {
              //由于这里的系统接口无监测到系统是否授权给蓝牙，统一写死已授权，(唯一检测到的是蓝牙相关接口)
              resolve({
                type: 'blue',
                content: [{
                  icon: 'checked',
                  color: "#02DD5B",
                  text: '当前蓝牙' + code[200]
                }, {
                  icon: 'checked',
                  color: "#02DD5B",
                  text: '蓝牙服务' + code[400]
                }],
                button: {
                  type: 200,
                  text: '确定'
                }
              })
            } else {
              reject({
                type: 'blue',
                desc: ['如您已快捷开启蓝牙，点击空白处后进行重新连接', '如无法跳转,请手动下拉/上拉开启蓝牙'],
                content: [{
                  icon: 'clear',
                  color: 'red',
                  text: '当前蓝牙' + code[500]
                }, {
                  icon: 'checked',
                  color: "#02DD5B",
                  text: '蓝牙服务' + code[400]
                }],
                button: {
                  type: 500,
                  text: '前往开启蓝牙'
                }
              })
            }
          } else {
            /**
             * IOS 可以检查是否开启和是否授权
             * bluetoothAuthorized 字段，ios没有微信授权是没有该字段的，要分开判断
             * */
            console.log(res.bluetoothEnabled != '', res.bluetoothAuthorized, res.bluetoothAuthorized ? true : false);
            if (typeof (res.bluetoothAuthorized) != 'undefined') {
              if (res.bluetoothEnabled && res.bluetoothAuthorized) {
                resolve({
                  type: 'blue',
                  desc: [],
                  content: [{
                    icon: 'checked',
                    color: "#02DD5B",
                    text: '当前蓝牙' + code[200]
                  }, {
                    icon: 'checked',
                    color: "#02DD5B",
                    text: '蓝牙服务' + code[400]
                  }],
                  button: {
                    type: 200,
                    text: '确定'
                  }
                })
              } else if (!res.bluetoothEnabled && res.bluetoothAuthorized) {
                reject({
                  type: 'blue',
                  desc: ['下拉/上滑开启【蓝牙】', '或前往手机【设置】—【蓝牙】开启', '再重新链接设备'],
                  content: [{
                    icon: 'clear',
                    color: "red",
                    text: '当前蓝牙' + code[500]
                  }, {
                    icon: 'checked',
                    color: '#02DD5B',
                    text: '蓝牙服务' + code[400]
                  }],
                  button: {
                    type: 500,
                    text: '确定'
                  }
                })
              } else if (res.bluetoothEnabled && !res.bluetoothAuthorized) {
                reject({
                  type: 'blue',
                  desc: ['***蓝牙授权后小程序将关闭，再次进入小程序扫码即可***'],
                  content: [{
                    icon: 'checked',
                    color: "#02DD5B",
                    text: '当前蓝牙' + code[200]
                  }, {
                    icon: 'clear',
                    color: 'red',
                    text: '蓝牙服务' + code[401]
                  }],
                  button: {
                    type: 401,
                    text: '前往授权蓝牙'
                  }
                })
              } else if (!res.bluetoothEnabled && !res.bluetoothAuthorized) {
                reject({
                  type: 'blue',
                  desc: ['下拉/上滑开启【蓝牙】', '或前往手机【设置】—【蓝牙】开启', '***蓝牙授权后小程序将关闭，再次进入小程序扫码即可***'],
                  content: [{
                    icon: 'clear',
                    color: 'red',
                    text: '蓝牙服务' + code[401]
                  }, {
                    icon: 'clear',
                    color: "red",
                    text: '当前蓝牙' + code[500]
                  }],
                  button: {
                    type: 401,
                    text: '前往授权蓝牙'
                  }
                })
              }
            } else {
              if (res.bluetoothEnabled) {
                resolve({
                  type: 'blue',
                  desc: [],
                  content: [{
                    icon: 'checked',
                    color: "#02DD5B",
                    text: '当前蓝牙' + code[200]
                  }, {
                    icon: 'checked',
                    color: "#02DD5B",
                    text: '蓝牙服务' + code[400]
                  }],
                  button: {
                    type: 200,
                    text: '确定'
                  }
                })
              } else {
                reject({
                  type: 'blue',
                  desc: ['下拉/上滑开启【蓝牙】', '或前往手机【设置】—【蓝牙】开启', '再重新链接设备'],
                  content: [{
                    icon: 'clear',
                    color: "red",
                    text: '当前蓝牙' + code[500]
                  }, {
                    icon: 'checked',
                    color: '#02DD5B',
                    text: '蓝牙服务' + code[400]
                  }],
                  button: {
                    type: 500,
                    text: '确定'
                  }
                })
              }
            }
          }
        }
      },
      fail: err => {
        let text = type == 'location' ? '定位' : '蓝牙'
        reject({
          type: type,
          desc: desc,
          content: [{
            icon: 'clear',
            color: 'red',
            text: '当前' + text + code[500]
          }, {
            icon: 'clear',
            color: 'red',
            text: text + '服务' + code[401]
          }],
          button: {
            type: 500,
            text: '确定'
          }
        })
      }
    })
  })
}

/**
 * 进场 和 出场动画
 * @param {*} that 当前对象
 * @param {*} distance 距离
 * @param {*} time 时间 ms
 * @param {*} length 长度
 */
export function showAnimation(that, length, distance, time = 300) {
  let animationTime = 0;
  for (let i = 0; i < length; i++) {
    let key = 'animation.animation' + i;
    let value = 'animation' + i;
    //字符串解析同名变量
    setTimeout(() => {
      that.setData({
        [key]: slideupshow(that, value, distance, 1, true)
      })
    }, animationTime);
    animationTime += time;
  }
}


const enSureHeader = ((header, type) => {
  //自定义头部
  if (header) {
    return header;
  } else {
    //内部接口头部
    return {
      'content-type': type ? type : 'application/x-www-form-urlencoded'
    }
  }
})

/**
 * 网络请求接口
 */
export function requestInterfce(url, data, method = 'post', type, header, ) {
  return new Promise((resolve, reject) => {
    wx.request({
      url: url.indexOf('http') > -1 ? url : enSureUrl(url),
      data: data,
      method: method,
      header: enSureHeader(header, type),
      success: (res => {
        resolve(res);
      }),
      fail: (err => {
        reject(err);
      })
    })
  })
}

/**
 * 
 * @param {*} count  图片张数
 * @param {*} mediaType  类型
 */
export function selectPhoto(count = 1, mediaType = 'image') {
  return new Promise((resolve, reject) => {
    wx.chooseMedia({
      count: count,
      mediaType: mediaType,
      success: res => {
        resolve(res);
      },
      fail: err => {
        reject(err);
      }
    })
  })
}

/**
 * param 返回上一页携带的数据对象
 * type： 是否在上一页对该param 进行处理 (false :不处理 ； true:  处理)
 * size: 要返回页面栈层数
 */
export function back(param = {}, type = false, size = 1) {
  let pages = getCurrentPages();
  let currentPage = pages[pages.length - (size > 2 ? size - 1 : 2)];
  currentPage.setData({
    param: param,
    type: type
  });
  setTimeout(() => {
    wx.navigateBack({
      delta: size,
    })
  }, 300);
}